package com.jmpt.fangbohui.ui.personalcenter;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jmpt.fangbohui.Constants;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.bean.AddBBClientAddressBean;
import com.jmpt.fangbohui.bean.AddBBClientAddressBean.Retval.date_distinct;
import com.jmpt.fangbohui.bean.AddBBClientAddressBean.Retval.date_house;
import com.jmpt.fangbohui.bean.LoginBean;
import com.jmpt.fangbohui.dao.LoginSQLiteOperator;
import com.jmpt.fangbohui.ui.base.BaseActivity;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;

/**
 * 
 * ClassName: AddBBClientActivity date: 2015-5-26 上午11:39:50
 * 
 * @author Lee
 * @since JDK 1.7
 */
public class AddBBClientActivity extends BaseActivity implements
		OnClickListener, OnItemSelectedListener {

	protected static final String TAG = "AddBBClientActivity";
	private ImageButton btn_base_head_left_imgbutton;
	private Button bt_activity_add_bb_client_config;
//	private EditText et_activity_add_client_house_id;
	private EditText et_activity_add_client_phone;
	private EditText et_activity_add_client_name;

	private SharedPreferences sp;
	private Spinner sp_add_client_distinct;
	private Spinner sp_add_client_house;

	private List<String> city;
	private List<String> house;
	private AddBBClientAddressBean address;
	private List<Integer> cityIds;
	private List<Integer> houseIds;
	private int cityId;
	private int houseId;
	
	public final static int SUCCESS = 200;
	public final static int FAILED = 202;

	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case SUCCESS:

				ToastHelper.ShowToast("操作成功", AddBBClientActivity.this);
				finish();
			break;
			case FAILED:

				ToastHelper.ShowToast("操作失败", AddBBClientActivity.this);
				
			break;
			}
			
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initView();
		initData();
		initEvent();
	}

	// 初始化数据，本地提取缓存下拉框，再到网上更新
	private void initData() {
		sp = getSharedPreferences("config", MODE_PRIVATE);
		String cacheCity = sp.getString(Constants.SharedPreferences.CACHECITY,
				null);
		if (TextUtils.isEmpty(cacheCity)) {
			Log.i(TAG, "cacheCity  != null");
			parsersAddress(cacheCity);
		}
		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.GET, Constants.URL.ADDCLIENTADDRESSURL,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						Log.i(TAG, arg1);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						sp.edit()
								.putString(
										Constants.SharedPreferences.CACHECITY,
										arg0.result).commit();
						parsersAddress(arg0.result);
					}
				});

	}

	protected void parsersAddress(String result) {
		Gson gson = new Gson();
		address = gson.fromJson(result,
				AddBBClientAddressBean.class);
		// 拆分数据
		if(address!=null){
			splitList(address);
		}
	}

	private void splitList(AddBBClientAddressBean address) {
		// 城市
		List<date_distinct> distinction = address.retval.date_distinct;
		city = new ArrayList<String>();
		cityIds = new ArrayList<Integer> ();
		for (date_distinct date_distinct : distinction) {
			city.add(date_distinct.name);
			cityIds.add(date_distinct.id);
		}

		// 设置下拉框的内容
		ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, city);
		sp_add_client_distinct.setAdapter(cityAdapter);

	}

	private void initEvent() {
		btn_base_head_left_imgbutton.setOnClickListener(this);
		bt_activity_add_bb_client_config.setOnClickListener(this);
		sp_add_client_distinct.setOnItemSelectedListener(this);
		sp_add_client_house.setOnItemSelectedListener(this);
	}

	private void initView() {
		setContentView(R.layout.activity_add_bb_client);

		bt_activity_add_bb_client_config = (Button) findViewById(R.id.bt_activity_add_bb_client_config);
//		et_activity_add_client_house_id = (EditText) findViewById(R.id.et_activity_add_client_house_id);
		et_activity_add_client_name = (EditText) findViewById(R.id.et_activity_add_client_name);
		et_activity_add_client_phone = (EditText) findViewById(R.id.et_activity_add_client_phone);
		sp_add_client_distinct = (Spinner) findViewById(R.id.sp_add_client_distinct);
		sp_add_client_house = (Spinner) findViewById(R.id.sp_add_client_house);

		btn_base_head_left_imgbutton = (ImageButton) findViewById(R.id.btn_base_head_left_imgbutton);
		TextView tv_base_head_title = (TextView) findViewById(R.id.tv_base_head_title);
		Button btn_base_head_right_button = (Button) findViewById(R.id.btn_base_head_right_button);
		tv_base_head_title.setText("新增报备客户");
		btn_base_head_left_imgbutton.setVisibility(View.VISIBLE);
		btn_base_head_right_button.setVisibility(View.GONE);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_base_head_left_imgbutton:
			finish();
			break;
		case R.id.bt_activity_add_bb_client_config:
			submit();
			break;

		}
	}

	private void submit() {
		final String phone = et_activity_add_client_phone.getText().toString().trim();
		if(!checkPhone(phone)){
			ToastHelper.ShowToast("电话长度不符合11位", this);
			return;
		}
		
		final String name = et_activity_add_client_name.getText().toString().trim();
		LoginSQLiteOperator dao = new LoginSQLiteOperator(this);
		LoginBean query = dao.query();
		String broker = query.getRetval().getAgentId();
		if (TextUtils.isEmpty(name)) {
			ToastHelper.ShowToast("客户姓名不能为空", this);
			return;
		}
		if (TextUtils.isEmpty(phone)) {
			ToastHelper.ShowToast("客户电话不能为空", this);
			return;
		}
		if (TextUtils.isEmpty(broker)) {
			ToastHelper.ShowToast("经纪人id不能为空", this);
			return;
		}


		LoginSQLiteOperator oper = new LoginSQLiteOperator(this);
		final List<String> querySessionId = oper.querySessionId();
		if(querySessionId.size() != 2){
			return;
		}
		
		new Thread(){
			public void run() {
				HttpClient httpClient = new DefaultHttpClient();
				try {
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("phone",phone));
					params.add(new BasicNameValuePair("username",name));
					params.add(new BasicNameValuePair("houseid", houseId+""));
					params.add(new BasicNameValuePair("zoneid", cityId+""));
					params.add(new BasicNameValuePair("userid",querySessionId.get(0)));
					
				    HttpPost postMethod = new HttpPost(Constants.URL.ADDCLIENTURL);
				    postMethod.setHeader("Cookie", "PHPSESSID=" + querySessionId.get(1)); 
				    postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中
								
				    HttpResponse response = httpClient.execute(postMethod); //执行POST方法
				    DebugLog.i("resCode = " + response.getStatusLine().getStatusCode());
				    
				    if(response.getStatusLine().getStatusCode() != 200){
				    	ToastHelper.ShowToast("网络不畅通，请稍后再试", AddBBClientActivity.this);
				    	return;
				    }
				    parsers(EntityUtils.toString(response.getEntity(), "utf-8"));
				    
								
				} catch (Exception e) {
				    e.printStackTrace();
				} 
			};
		}.start();

	}

	private boolean checkPhone(String phone) {
		if(phone.length()!=11){
			return false;
		}
		return true;
	}

	protected void parsers(String result) {
		Gson gson = new Gson();
		DebugLog.i(result);
		Result real = gson.fromJson(result, Result.class);
		Message obtain = Message.obtain();
		if ("true".equals(real.done)) {
			obtain.what = SUCCESS;
		} else {

			obtain.what = FAILED;
		}
		handler.sendMessage(obtain);
	}
/*
 *  {"done":"false","msg":"\u91cd\u590d\u62a5\u5907","retval":{"flag":"Failure","Reason":"\u91cd\u590d\u62a5\u5907"}}

 */
	private class Result {
		private  String done;
		private String msg;
		private Retval retval;
		public class Retval{
			private String flag;
			private String Reason;
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		if(sp_add_client_distinct == parent){
			int realPosition = position + 1;
			cityId = cityIds.get(position);
			// 设置楼盘
			house = new ArrayList<String>();
			houseIds = new ArrayList<Integer> ();
			List<date_house> date_house = address.retval.date_house;
			for (date_house date_house2 : date_house) {
				if(date_house2.zoneid.equals(realPosition+"")){
					house.add(date_house2.title);
					houseIds.add(date_house2.id);
				}
			}
			ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_dropdown_item,house);
			sp_add_client_house.setAdapter(cityAdapter);
		}
		if(sp_add_client_house == parent){
			houseId = houseIds.get(position);
			Log.i(TAG, houseId+"");
		}
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

}
